import { View } from "@tarojs/components";
import AddressRow from "@/pages/address/components/address-row";
import { useImmer } from "use-immer";
import { AddressDto } from "@/apis/__generated/model/dto";
import Taro from "@tarojs/taro";
import { api } from "@/utils/api-instance";
import { Del, Edit, Plus } from "@nutui/icons-react-taro";
import { switchPage } from "@/utils/common";
import { ActionSheet } from "@nutui/nutui-react-taro";
import "./address-list.scss";

type MenuName = "复制地址" | "设为默认";
type MenuItem = { name: MenuName };
type Address = AddressDto["AddressRepository/COMPLEX_FETCHER_FOR_FRONT"];
export default function AddressList() {
  const [addressList, setAddressList] = useImmer<Address[]>([]);
  const [activeAddress, setActiveAddress] = useImmer<Address | undefined>(
    undefined,
  );
  const [addressEvent, setAddressEvent] = useImmer("");

  const handleAddressChoose = (value: Address) => {
    if (addressEvent) {
      Taro.navigateBack({
        success() {
          Taro.eventCenter.trigger(addressEvent, value);
        },
      });
    }
  };
  const actions = [
    { name: "复制地址" },
    { name: "设为默认" },
  ] satisfies MenuItem[];
  const actionMap = {
    ["复制地址"]: () => {
      // 复制地址到剪贴板
      if (!activeAddress) return;
      const value = `收件人：${activeAddress.realName}\n手机号码：${activeAddress.phoneNumber}\n详细地址：${activeAddress.details} ${activeAddress.houseNumber}`;
      Taro.setClipboardData({ data: value });
    },
    ["设为默认"]: async () => {
      // 设置默认地址
      if (!activeAddress) return;
      await api.addressForFrontController.top({ id: activeAddress.id });
      await loadData();
    },
  };
  // 选择菜单后触发
  const handleActionChoose = (action: MenuItem) => {
    // 执行对应的操作
    actionMap[action.name]();
  };
  // 长按地址后触发，显示
  const showActionSheet = (address: Address) => {
    setActiveAddress(address);
    setVisible(true);
  };
  const [visible, setVisible] = useImmer(false);
  const loadData = async () => {
    const res = await api.addressForFrontController.query({
      body: {
        pageSize: 1000,
        pageNum: 1,
        query: {},
      },
    });
    setAddressList([...res.content]);
  };
  Taro.useLoad(async ({ event }) => {
    if (event) {
      setAddressEvent(event);
    }
  });
  Taro.useDidShow(async () => {
    await loadData();
    console.log("address-list");
  });

  const handleDelete = (id: string) => {
    Taro.showModal({
      title: "是否确认删除",
      showCancel: true,
      success: async ({ confirm }) => {
        if (confirm) {
          await api.addressForFrontController.delete({ body: [id] });
          await loadData();
        }
      },
    });
  };
  return (
    <View className="address-list">
      {addressList.map((row) => {
        return (
          <View
            onClick={() => handleAddressChoose(row)}
            onLongPress={() => showActionSheet(row)}
            key={row.id}
          >
            <AddressRow
              address={row}
              operation={
                <View>
                  <Del
                    className="delete"
                    onClick={() => handleDelete(row.id)}
                  ></Del>
                  <Edit
                    className="edit"
                    onClick={(e) => {
                      e.stopPropagation();
                      switchPage(`./address-save?id=${row.id}`);
                    }}
                  ></Edit>
                </View>
              }
            ></AddressRow>
          </View>
        );
      })}
      <View className="add" onClick={() => switchPage("./address-save")}>
        <View className="btn">
          <Plus></Plus>
          添加收货地址
        </View>
      </View>
      <ActionSheet
        options={actions}
        visible={visible}
        onSelect={handleActionChoose}
      ></ActionSheet>
    </View>
  );
}
